

#include "list_node.h"

list_node_t* list_node_get_at(list_node_t** pp_head, int idx)
{
    if( *pp_head == NULL )
    {
        return NULL;
    }

    if( idx == 0 )
    {
        return *pp_head;
    }

    list_node_t* p_node = *pp_head;
    int index = 0;
    while( p_node != NULL )
    {
        if( idx == index)
        {
            return p_node;
        }
        p_node = p_node->p_next;
        ++index;
    }

    return NULL;
}

list_node_t* list_node_get_last(list_node_t** pp_head)
{
    if( *pp_head == NULL )
    {
        return NULL;
    }

    list_node_t* p_node = (*pp_head)->p_next;
    while( p_node->p_next != NULL )
    {
        p_node = p_node->p_next;
    }

    return p_node;
}

void list_node_add( list_node_t** pp_head, list_node_t* p_new)
{
    if( *pp_head == NULL )
    {
        *pp_head = p_new;
        (*pp_head)->p_next = NULL;
    }
    else 
    {
        list_node_t* p_node = *pp_head;
        while( p_node != NULL )
        {
            p_node = p_node->p_next;
        }

        list_node_insert( p_node, p_new );
    }
}

uint32_t list_node_size_get( list_node_t* p_head)
{
    if( p_head == NULL )
    {
        return 0;
    }

    int size = 1; 
    while( p_head->p_next != NULL )
    {
        p_head = p_head->p_next;
        ++size;
    }

    return size; 
}

uint32_t list_node_remove( list_node_t** pp_head, list_node_t* p_node)
{
    if(*pp_head == NULL || p_node == NULL)
    {
        return 1;
    }

    if( p_node == *pp_head)
    {
        *pp_head = p_node->p_next;
        p_node->p_next = NULL;

        return 0;
    }

    list_node_t* p_item = *pp_head;
    while( p_item->p_next != NULL && p_item->p_next != p_node)
    {
        p_item = p_item->p_next;
    }

    if( p_item == NULL || p_item->p_next != p_node)
    {
        return 1;
    }

    p_item->p_next = p_node->p_next;
    p_node->p_next = NULL;

    return 0; 
}

//list_node_t* list_next( list_node_t** pp_head )
//{
//    if( *pp_head == NULL ) 
//    {
//        return NULL;
//    }
//    
//}
